package com.san.common.aspect;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.san.base.domain.ReportLogDO;
import com.san.base.service.ReportLogService;
import com.san.common.annotation.ReportLog;
import com.san.common.utils.HttpContextUtils;
import com.san.common.utils.IPUtils;
import com.san.common.utils.ShiroUtils;

@Aspect
@Component
public class ReportLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(ReportLogAspect.class);

    @Autowired
    ReportLogService reportLogService;


    @Pointcut("@annotation(com.san.common.annotation.ReportLog)")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        // 执行方法
        Object result = point.proceed();
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //异步保存日志
        saveLog(point, time);
        return result;
    }

    void saveLog(ProceedingJoinPoint joinPoint, long time) throws InterruptedException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        ReportLogDO ReportLogDO = new ReportLogDO();
        ReportLog reportLog = method.getAnnotation(ReportLog.class);
        if (reportLog != null) {
            // 注解上的描述
        	ReportLogDO.setType(reportLog.value());
        }
        // 请求的参数
        Object[] args = joinPoint.getArgs();
        try {
        	if (args.length > 0) {
        		String params = args[1].toString();
        		ReportLogDO.setPersonId(params);
        	}
        } catch (Exception e) {
        	logger.error("参数转换错误",e);
        }
        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        // 设置IP地址
        ReportLogDO.setIp(IPUtils.getIpAddr(request));
        // 用户名
        	ReportLogDO.setUserId(ShiroUtils.getUserId());
        	ReportLogDO.setUserName(ShiroUtils.getUser().getUserName());
        // 系统当前时间
        Date date = new Date();
        ReportLogDO.setCreateDate(date);
        // 保存系统日志
        try {
        	reportLogService.save(ReportLogDO);
		} catch (Exception e) {
			logger.error("日志保存失败",e);
		}
    }
}
